import { NodeViewWrapper } from '@tiptap/react';
import { useEditorStore } from '@/store/useEditorZustand';
import { Blocks } from 'lucide-react';
import { mergeAttributes, Node } from '@tiptap/core';
import { Button } from 'antd';
import { ReactNodeViewRenderer } from '@tiptap/react';

const CustomBlock = (props) => {
  const increase = () => {
    props.updateAttributes({
      count: props.node.attrs.count + 1,
    });
  };

  return (
    <NodeViewWrapper className="react-component">
      <Button onClick={increase}>
        This button has been clicked {props.node.attrs.count} times.
      </Button>
    </NodeViewWrapper>
  );
};
// 注册自定义节点
const NodeCreate = Node.create({
  name: 'reactComponent',
  group: 'block',
  atom: true, // 原子节点，不能有任何content
  addAttributes() {
    return {
      count: {
        default: 0,
      },
    };
  },
  parseHTML() {
    return [
      {
        tag: 'react-component',
      },
    ];
  },

  renderHTML({ HTMLAttributes }) {
    return ['react-component', mergeAttributes(HTMLAttributes)];
  },

  addNodeView() {
    return ReactNodeViewRenderer(CustomBlock);
  },
});

export default NodeCreate;

const InsertBlock = function () {
  const { editor } = useEditorStore();

  const handler = function () {
    editor
      ?.chain()
      .focus()
      .insertContentAt(editor.state.selection.to, {
        type: 'reactComponent',
        attrs: { count: 0 },
      })
      .run();
  };

  return <Button icon={<Blocks className="size-4" />} type="text" onClick={handler} />;
};

export { InsertBlock };
